<template>
  <div class="case-management-container">
    <el-card class="main-card">
      <!-- 查询表单 -->
      <div class="search-section">
        <el-form :model="queryParams" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="案件名称">
                <el-input v-model="queryParams.caseName" placeholder="请输入案件名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="案件状态">
                <el-select v-model="queryParams.status" placeholder="请选择案件状态" clearable>
                  <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="案件类型">
                <el-select v-model="queryParams.caseType" placeholder="请选择案件类型" clearable>
                  <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="display: flex; align-items: center; justify-content: flex-end">
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 案件列表 -->
      <div class="table-section">
        <el-table v-loading="loading" :data="caseList" border style="width: 100%" height="calc(100vh - 357px)">
          <el-table-column prop="caseName" label="案件名称" width="300" />
          <el-table-column prop="status" label="案件状态" width="170">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)" :style="getStatusStyle(row.status)">
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="caseType" label="案件类型" width="170">
            <template #default="{ row }">
              {{ getTypeLabel(row.caseType) }}
            </template>
          </el-table-column>
          <el-table-column prop="applicant" label="申请人" width="150" />
          <el-table-column prop="phone" label="电话号码" width="150" />
          <el-table-column label="承办律师" width="150">
  <template #default="{ row }">
    {{ getLawyerName(row.lawyerId) }}
  </template>
</el-table-column>
          <el-table-column label="操作" fixed="right">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click="handleDetail(row)">
                查看详细
              </el-button>
              <el-button size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <!-- <div class="pagination-container">
          <el-pagination v-model:current-page="queryParams.page" v-model:page-size="queryParams.pageSize" :total="total"
            :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div> -->
      </div>
    </el-card>
  </div>


  <el-dialog v-model="dialogVisible" :title="isEditMode ? '编辑案件' : '案件详情'" width="70%">
    <div v-if="currentCaseDetail">
      <el-tabs type="border-card">
        <el-tab-pane label="基本信息">
          <template v-if="!isEditMode">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="案件编号">{{ currentCaseDetail.caseNo }}</el-descriptions-item>
              <el-descriptions-item label="案件名称">{{ currentCaseDetail.caseName }}</el-descriptions-item>
              <el-descriptions-item label="案件类型">{{ getTypeLabel(currentCaseDetail.caseType) }}</el-descriptions-item>
              <el-descriptions-item label="案件状态">
                <el-tag :type="getStatusTagType(currentCaseDetail.status)"
                  :style="getStatusStyle(currentCaseDetail.status)">
                  {{ getStatusLabel(currentCaseDetail.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="申请人">{{ currentCaseDetail.applicant }}</el-descriptions-item>
              <el-descriptions-item label="真实姓名">{{ currentCaseDetail.realName }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ currentCaseDetail.phone }}</el-descriptions-item>
              <el-descriptions-item label="承办律师">{{ getLawyerName(currentCaseDetail.lawyerId) }}</el-descriptions-item>
              <el-descriptions-item label="申请时间">{{ currentCaseDetail.applyTime }}</el-descriptions-item>
            </el-descriptions>
          </template>
          <template v-else>
            <el-form :model="editForm" label-width="100px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="案件名称">
                    <el-input v-model="editForm.caseName" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="案件类型">
                    <el-select v-model="editForm.caseType">
                      <el-option v-for="item in typeOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="案件状态">
                    <el-select v-model="editForm.status">
                      <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="承办律师">
                    <el-select v-model="editForm.lawyerId">
                      <el-option v-for="item in lawyerList" :key="item.lawyerId" :label="item.name"
                        :value="item.lawyerId" />
                    </el-select>
                  </el-form-item>

                </el-col>
                <!-- <el-col :span="12">
                  <el-form-item label="申请人">
                    <el-input v-model="editForm.applicant" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="真实姓名">
                    <el-input v-model="editForm.realName" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="联系电话">
                    <el-input v-model="editForm.phone" />
                  </el-form-item>
                </el-col> -->
              </el-row>
            </el-form>
          </template>
        </el-tab-pane>
        <el-tab-pane label="案件描述">
          <template v-if="!isEditMode">
            <p>{{ currentCaseDetail.description }}</p>
            <el-divider />
            <p style="white-space: pre-wrap;">{{ currentCaseDetail.content }}</p>
          </template>
          <template v-else>
            <el-form :model="editForm" label-width="100px">
              <el-form-item label="案件描述">
                <el-input type="textarea" v-model="editForm.description" rows="2" />
              </el-form-item>
            </el-form>
          </template>
        </el-tab-pane>
        <el-tab-pane label="附件">
          <el-table :data="currentCaseDetail.materials" border>
            <el-table-column prop="materialName" label="文件名" />
            <el-table-column label="操作" align="center">
              <template v-slot:default="{ row }">
                <el-button type="text" @click="downloadAttachment(row.materialId, row.materialName)">下载</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

      </el-tabs>
      <template v-if="isEditMode">
        <div style="text-align:right;margin-top:20px;">
          <el-button type="primary" @click="handleSaveEdit" :loading="loading">保存</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </template>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { CaseApi } from '@/api/case'
import { LawyerApi } from '@/api/lawyer'
import { ElMessage, ElMessageBox } from 'element-plus'

const dialogVisible = ref(false)
const currentCaseDetail = ref(null)
const isEditMode = ref(false)
const editForm = reactive({})
const lawyerList = ref([])


// 查询参数
const queryParams = ref({
  page: 1,
  pageSize: 10,
  caseName: '',
  status: '',
  caseType: ''
})

// 案件状态选项
const statusOptions = ref([
  { value: 'draft', label: '草稿' },
  { value: 'reviewing', label: '审核中' },
  { value: 'approved', label: '已批准' },
  { value: 'rejected', label: '已拒绝' },
  { value: 'processing', label: '处理中' },
  { value: 'completed', label: '已完成' }
])

// 案件类型选项
const typeOptions = ref([
  { value: 'CIVIL', label: '民事案件' },
  { value: 'CRIMINAL', label: '刑事案件' },
  { value: 'ADMINISTRATIVE', label: '行政案件' }
])

// 案件列表数据
const caseList = ref([])
const loading = ref(false)

// 获取案件列表
const getCaseList = async () => {
  try {
    loading.value = true
    const res = await CaseApi.getCaseList(queryParams.value)
    console.log('案件列表数据:', res)
    caseList.value = res.data || []
  } catch (error) {
    console.error('获取案件列表失败:', error)
    caseList.value = []
  } finally {
    loading.value = false
  }
}

// 查询按钮点击事件
const handleQuery = () => {
  queryParams.value.page = 1
  getCaseList()
}

// 重置查询条件
const resetQuery = () => {
  queryParams.value = {
    // page: 1,
    // pageSize: 10,
    caseName: '',
    status: '',
    caseType: ''
  }
  getCaseList()
}

// 分页大小改变
// const handleSizeChange = (val) => {
//   queryParams.value.pageSize = val
//   getCaseList()
// }

// 当前页改变
// const handleCurrentChange = (val) => {
//   queryParams.value.page = val
//   getCaseList()
// }

// 查看详情
const handleDetail = async (row) => {
  try {
    loading.value = true
    const res = await CaseApi.getCaseDetail(row.id)
    currentCaseDetail.value = res.data
    isEditMode.value = false
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取案件详情失败')
    console.error('获取案件详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 编辑案件
const handleEdit = async (row) => {
  try {
    loading.value = true
    const res = await CaseApi.getCaseDetail(row.id)
    currentCaseDetail.value = res.data
    Object.assign(editForm, res.data)
    isEditMode.value = true
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取案件详情失败')
    console.error('获取案件详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 保存编辑
const handleSaveEdit = async () => {
  try {
    loading.value = true
    await CaseApi.updateCase(editForm.id, editForm)
    ElMessage.success('保存成功')
    dialogVisible.value = false
    getCaseList()
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    loading.value = false
  }
}
// 删除案件
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除案件 "${row.caseName}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await CaseApi.deleteCase(row.id)
    ElMessage.success('删除成功')
    getCaseList()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const map = {
    draft: 'warning',
    reviewing: 'info',
    approved: 'primary',
    rejected: 'danger',
    processing: '',
    completed: 'success'
  }
  return map[status] || ''
}

// 获取状态标签样式
const getStatusStyle = (status) => {
  if (status === 'processing') {
    return { backgroundColor: '#722ed1', color: '#fff' };
  }
  return {};
}

// 下载附件
const downloadAttachment = (materialId, materialName) => {
  CaseApi.downloadMaterial(materialId)
    .then(response => {
      const blob = new Blob([response.data]);
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = materialName;
      document.body.appendChild(link);
      link.click();
      window.URL.revokeObjectURL(url);
      this.$notify({
        title: '成功',
        message: '文件下载成功',
        type: 'success'
      });
    })
    .catch(error => {
      this.$notify({
        title: '失败',
        message: `文件下载失败: ${error.message || '未知错误'}`,
        type: 'error'
      });
    });
}

// 获取状态显示文本
const getStatusLabel = (status) => {
  const item = statusOptions.value.find(opt => opt.value === status)
  return item ? item.label : status
}

// 获取类型显示文本
const getTypeLabel = (type) => {
  const item = typeOptions.value.find(opt => opt.value === type)
  return item ? item.label : type
}

const getLawyerName = (lawyerId) => {
  const lawyer = lawyerList.value.find(lawyer => lawyer.lawyerId === lawyerId)
  return lawyer ? lawyer.name : lawyerId
}

// 组件挂载时获取初始数据
onMounted(async () => {
  getCaseList()
  const res = await LawyerApi.getLawyerList()
  lawyerList.value = res.data
  console.log('律师列表数据:', lawyerList.value)


})
</script>

<style scoped>
.search-section {
  margin-bottom: 20px;
}

.table-section {
  position: relative;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  position: sticky;
  bottom: 0;
  background: white;
  padding: 10px 0;
  z-index: 1;
}
</style>